package no.saiboten.tourbuilder.bracket.controller;

import no.saiboten.tourbuilder.bracket.BracketDAO;
import no.saiboten.tourbuilder.bracket.BracketService;
import no.saiboten.tourbuilder.tournament.service.TournamentService;
import no.saiboten.tourbuilder.user.UserStatus;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping("/bracket")
public class BracketController {

	@Autowired
	BracketService bracketService;

	@Autowired
	BracketDAO bracketDAO;

	@Autowired
	TournamentService tournamentService;

	@Autowired
	UserStatus userStatus;

	private final Logger LOGGER = Logger.getLogger(getClass());

	@RequestMapping(value = "", method = RequestMethod.GET)
	public ModelAndView getBracket() {
		ModelAndView mav = new ModelAndView("bracket/brackets");
		mav.addObject("brackets", bracketDAO.getAllBrackets());
		LOGGER.debug("Returning brackets: " + bracketDAO.getAllBrackets());
		return mav;
	}

	@RequestMapping(value = "/get/{bracketId}", method = RequestMethod.GET)
	public ModelAndView getBracket(@PathVariable String bracketId) {
		ModelAndView mav = new ModelAndView("bracket/bracket");
		mav.addObject("user", userStatus);
		mav.addObject("bracket", bracketDAO.getBracket(bracketId));
		LOGGER.debug("Returning bracket: " + bracketDAO.getBracket(bracketId));
		return mav;
	}

	@RequestMapping(value = "/admin/createBracket/{tournamentId}")
	public RedirectView createBracket(@PathVariable String tournamentId) {
		RedirectView mav = new RedirectView("/tourbuilder/bracket");
		bracketService.createBracket(tournamentService
				.getTournament(tournamentId));
		return mav;
	}

	@RequestMapping("/reportloss")
	public String reportLoss(@RequestParam String bracketId,
			@RequestParam int pointsFor, @RequestParam int pointsAgainst) {
		if (userStatus.isAuthenticated()) {
			if (bracketService.isUserStillPlaying(userStatus
					.getUser().getUserName(), bracketId)) {
				bracketService.reportLoss(bracketId, userStatus
						.getUser().getUserName(), pointsFor,
						pointsAgainst);
			} else {
				LOGGER.debug("User is not in the tournament ..");
			}

		} else {
			LOGGER.debug("User it not authenticated");
		}
		return "bracket/loss";
	}
}
